package main

import (
	"apps/cqrs-example/internal/products/api"
	"apps/cqrs-example/internal/products/features/creating_product/commands"
	"apps/cqrs-example/internal/products/repository"
	"apps/cqrs-example/internal/shared/behaviors"
	"context"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/labstack/echo/v4"
	"github.com/mehdihadeli/go-mediatr"
)

func main() {
	ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
	defer cancel()

	echo := echo.New()
	productRepository := repository.NewInMemoryProductRepository()

	createProductCommandHandler := commands.NewCreateProductCommandHandler(productRepository)

	err := mediatr.RegisterRequestHandler(createProductCommandHandler)
	if err != nil {
		log.Fatal(err)
	}

	loggerPipeline := &behaviors.RequestLoggerBehavior{}
	err = mediatr.RegisterRequestPipelineBehaviors(loggerPipeline)
	if err != nil {
		log.Fatal(err)
	}

	controller := api.NewProductsController(echo)
	api.MapProductRoutes(echo, controller)

	go func() {
		if err := echo.Start(":9080"); err != nil {
			log.Fatal("Error starting Server", err)
		}
	}()

	<-ctx.Done()
	if err := echo.Shutdown(ctx); err != nil {
		log.Fatal("Error shutting down Server", err)
	}
}
